$(document).ready(function(){
    laydate.skin('molv');/* 设置时间插件的皮肤 */
    var start = {
        elem: '#startTime', //选择ID为START的input
        format: 'YYYY-MM-DD', //自动生成的时间格式
        /*  min: laydate.now(), */ //设定最小日期为当前日期
        max: laydate.now(), //最大日期
        istoday: false,  //是否是当天
        start: laydate.now(0,"YYYY-MM-DD"),  //设置开始时间为当前时间
        choose: function(datas){
            over.min = datas; //开始日选好后，重置结束日的最小日期
            /*over.start = datas;*/ //将结束日的初始值设定为开始日
        }
    };
    var over = {
        elem: '#endTime',
        format: 'YYYY-MM-DD',
        max: laydate.now(),
        /* max: '2099-06-16 23:59:59',   */
        istoday: false,
        start: laydate.now(0,"YYYY-MM-DD"),
        choose: function(datas){
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(over);


    /*统计条件下拉框点击选项阻止收起事件*/
    $(".dropdown-menu").on("click","[data-stopPropagation]",function(e){
        e.stopPropagation();
    })

    var btnElement = '#SearchForm .dis,#userUseBtn .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限


    var url = "../employ/query";
    var organizationId = "";
    loaduserListTable(url,organizationId);

    /*加载组织机构树结构*/
    $.fn.zTree.init($("#treeDemo"), setting);

});

/*初始化加载数据表格*/
function loaduserListTable(url,organizationId){ //点击选择后执行的事件
    $('#userListTable').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
    /*获取搜索条件参数*/
   /* var organizationId =$("#SearchForm input[name='organizationId']").val();*/
    var userName =$("#SearchForm input[name='userName']").val();
    var menuName =$("#SearchForm input[name='menuName']").val();
    var start = $("#startTime").val()==''?null:$("#startTime").val()+" 00:00:00";
    var end = $("#endTime").val()==''?null:$("#endTime").val()+" 23:59:59";

    /*获取显示表头数据参数并去null和undefined*/
    var zzjg  = $('#userInventory input[name="zzjg"]:checked').val();
    if(zzjg==null||zzjg=="undefined"){
        zzjg="";
    }
    var yhm = $('#userInventory input[name="yhm"]:checked').val();
    if(yhm==null||yhm=="undefined"){
        yhm="";
    }
    var gn = $('#userInventory input[name="gn"]:checked').val();
    if(gn==null||gn=="undefined"){
        gn="";
    }
    var ff = $('#userInventory input[name="ff"]:checked').val();
    if(ff==null||ff=="undefined"){
        ff="";
    }
    var czsj = $('#userInventory input[name="czsj"]:checked').val();
    if(czsj==null||czsj=="undefined"){
        czsj="";
    }

    /*初始化表格*/
    $('#userListTable').bootstrapTable({
        method: 'POST',
        url:url,   /* 调用后台接口加载数据 */
        queryParamsType:'',
        queryParams:function (params) {
            var pageSize = params.pageSize;
            var pageNum = params.pageNumber;
            return {  /*参数*/
                page:pageNum,
                rows:pageSize,
                /*条件查询参数*/
                organizationId:organizationId,
                userName:userName,
                menuName:menuName,
                start:start,
                end:end,
                /*表格显示隐藏参数*/
                zzjg:zzjg,
                yhm:yhm,
                gn:gn,
                ff:ff,
                czsj:czsj
            };
        },
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",
        cache: false,     // 不缓存
        striped: true,    // 隔行加亮
        pagination: true, //是否显示分页
        toolbar: '#userUseBtn',//工具列
        /*singleSelect:true, //单选*/
        pageSize: 10,
        pageNumber: 1,     //初始化加载第一页，默认第一页
        pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
        /*search: true,*/
        sidePagination: "server",
        /*height:$(window).height() - 95,*/
        /*showColumns: true,*/
        showRefresh: true,  //是否显示刷新按钮
        /*clickToSelect: true,*/  //是否启用点击选中行
        columns: [
            /*{field: "checkStatus",title: "全选", checkbox:true, width: 50, align: "center", valign: "middle",
                formatter:function(value,row,index){
                    /!* console.log(value);*!/
                    return value;
                }
            },*/
            {field: 'num',title: '序号',width: 20,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
            {field:"userName",title:"用户名",align:"center",valign:"middle",sortable:"true"},
            {field:"organizationId",title:"组织机构",align:"center",valign:"middle",sortable:"true"},
            {field:"menuName",title:"功能",align:"center",valign:"middle",sortable:"true"},
            {field:"methodName",title:"方法",align:"center",valign:"middle",sortable:"true"},
            {field:"oprTime",title:"操作时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {return new Date(value).Format("yyyy-MM-dd")}},
            {field:"userId",title:"次数",align:"center",valign:"middle",sortable:"true"}
        ],
        formatLoadingMessage: function () {
            return "请稍等，正在加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        responseHandler: function(res) {
            var total ,rows;
            if (res!=null&&res.length!=0) {
                total = res.total;
                rows = res.rows;
            }else {
                total = 0;
                rows = new Array();
            }
            return {
                "total":total,//total,//总页数
                "rows":rows  //数据
            };
        }

    });

    //判断统计条件是否勾选，勾选则显示，未勾选则隐藏
    var obj = $("#userInventory input");
    for (var i = 0 ; i<obj.length; i++) {
        $('#userListTable').bootstrapTable('hideColumn', obj[i].value.toString());
        if(obj[i].type=="checkbox" && obj[i].checked){
            $('#userListTable').bootstrapTable('showColumn', obj[i].value.toString());
        }
    }

    $(window).resize(function (e, value, row, index) {
        $('#userListTable').bootstrapTable('resetView');
    });
};

/*按条件查询方法*/
function searchdata(){
    var url = "../employ/query";

    /*获取所有复选框选中项的值放入一个字符串中*/
    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
        nodes=treeObj.getCheckedNodes(true),
        organizationId=""; //按钮id
    for(var i=0;i<nodes.length;i++){
        organizationId += nodes[i].id+",";  //获取选中节点的值
    }
    //去掉最后一个逗号
    if (organizationId.length > 0) {
        organizationId = organizationId.substr(0, organizationId.length - 1);
    }
    loaduserListTable(url,organizationId);
}

/*统计项目内统计方法*/
function statInfo(){
    /*获取checkbox的选中项，判断选中项大于1则进行统计*/
    var chkobj = $("#userInventory input[type='checkbox']:checked");
    var url = "../employ/query";
    /*获取所有复选框选中项的值放入一个字符串中*/
    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
        nodes=treeObj.getCheckedNodes(true),
        organizationId=""; //按钮id
    for(var i=0;i<nodes.length;i++){
        organizationId += nodes[i].id+",";  //获取选中节点的值
    }
    //去掉最后一个逗号
    if (organizationId.length > 0) {
        organizationId = organizationId.substr(0, organizationId.length - 1);
    }
    if(chkobj.length<1){
        layer.msg("至少选择一个项目统计");
        return ;
    }else{
        loaduserListTable(url,organizationId);
    }
}

/*导出按钮点击事件*/
function loadData(){
    /*获取搜索条件参数*/
    /*获取所有复选框选中项的值放入一个字符串中*/
    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
        nodes=treeObj.getCheckedNodes(true),
        organizationId=""; //按钮id
    for(var i=0;i<nodes.length;i++){
        organizationId += nodes[i].id+",";  //获取选中节点的值
    }
    //去掉最后一个逗号
    if (organizationId.length > 0) {
        organizationId = organizationId.substr(0, organizationId.length - 1);
    }

    var userName =$("#SearchForm input[name='userName']").val();
    var menuName =$("#SearchForm input[name='menuName']").val();
    var start = $("#startTime").val()==''?null:$("#startTime").val()+" 00:00:00";
    var end = $("#endTime").val()==''?null:$("#endTime").val()+" 23:59:59";

    /*获取显示表头数据参数并去null和undefined*/
    var zzjg  = $('#userInventory input[name="zzjg"]:checked').val();
    if(zzjg==null||zzjg=="undefined"){
        zzjg="";
    }
    var yhm = $('#userInventory input[name="yhm"]:checked').val();
    if(yhm==null||yhm=="undefined"){
        yhm="";
    }
    var gn = $('#userInventory input[name="gn"]:checked').val();
    if(gn==null||gn=="undefined"){
        gn="";
    }
    var ff = $('#userInventory input[name="ff"]:checked').val();
    if(ff==null||ff=="undefined"){
        ff="";
    }
    var czsj = $('#userInventory input[name="czsj"]:checked').val();
    if(czsj==null||czsj=="undefined"){
        czsj="";
    }

    $.ajax({
        type: "POST",
        url:'../employ/dc',   /* 调用后台接口加载数据 */
        data:{ /*参数*/
            /*条件查询参数*/
            "organizationId":organizationId,
            "userName":userName,
            "menuName":menuName,
            "start":start,
            "end":end,
            /*表格显示隐藏参数*/
            "zzjg":zzjg,
            "yhm":yhm,
            "gn":gn,
            "ff":ff,
            "czsj":czsj
        },
        dataType:"json",
        success: function(result) {
            if(result.code==0){
                window.location.href = result.url;
            }else{
                layer.msg("文件不存在");
            }
        }
    })
}

var setting = {
    check: {
        enable: true,
        chkboxType: {"Y":"", "N":""}
    },
    view: {
        dblClickExpand: false
    },
    data: {
        key:{
            checked:"checked",
            children:"children",
            name:"orgName",
            title:"",
            url:""
        },
        simpleData: {
            enable:true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: ""
        }
    },
    async : {
        enable : true,
        url : "../organ/query",
        dataFilter: filter
    },
    callback: {
        beforeClick: beforeClick,
        onCheck: onCheck
    }
};

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i=0, l=childNodes.length; i<l; i++) {
        childNodes[i].orgName = childNodes[i].orgName.replace(/\.n/g, '.');
    }
    return childNodes;
}

function beforeClick(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    zTree.checkNode(treeNode, !treeNode.checked, null, true);
    return false;
}

function onCheck(e, treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getCheckedNodes(true),
        v = "";
    for (var i=0, l=nodes.length; i<l; i++) {
        v += nodes[i].orgName + ",";
    }
    if (v.length > 0 ) v = v.substring(0, v.length-1);
    var cityObj = $("#citySel");
    cityObj.attr("value", v);
}

function showMenu() {
    var cityObj = $("#citySel");
    var cityOffset = $("#citySel").offset();
    $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
    /*$("#menuBtn").removeClass("fa fa-chevron-down").addClass("fa fa-chevron-up");*/
}
function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
    /*$("#menuBtn").removeClass("fa fa-chevron-up").addClass("fa fa-chevron-down");*/
}
function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "citySel" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}

// 对Date的扩展，将 Date 转化为指定格式的String
Date.prototype.Format = function (fmt) { //author: zhengsh 2016-9-5
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
